<template>
  <div class="exam-replay">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试过程回放</span>
        </div>
      </template>
      <!-- 筛选条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="考试名称">
          <el-select v-model="searchForm.examId" placeholder="请选择考试" clearable @change="onExamChange">
            <el-option
              v-for="exam in examList"
              :key="exam.examId"
              :label="exam.title"
              :value="exam.examId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学生">
          <el-select v-model="searchForm.studentId" placeholder="请选择学生" clearable @change="fetchReplayData">
            <el-option
              v-for="student in uniqueStudentList"
              :key="student.studentId"
              :label="student.name + '（' + student.studentId + '）'"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 回放时间线 -->
      <div v-if="timeline.length > 0" class="replay-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="item in timeline"
            :key="item.key"
            :timestamp="item.time"
            :type="item.type"
          >
            <template v-if="item.kind === 'event'">
              <el-tag :type="item.type" style="margin-bottom: 8px;">{{ item.eventType }}</el-tag>
              <span>{{ item.desc }}</span>
            </template>
            <template v-else-if="item.kind === 'screenshot'">
              <el-tag type="info" style="margin-bottom: 8px;">截图</el-tag>
              <el-image
                :src="item.imgUrl"
                :preview-src-list="[item.imgUrl]"
                fit="contain"
                style="width: 120px; height: 80px; cursor: pointer; border: 1px solid #eee; margin-top: 4px;"
              />
            </template>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div v-else class="empty-tip">
        <el-empty description="请选择考试和学生，查看回放数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const searchForm = reactive({
  examId: '',
  studentId: ''
})

const examList = ref<any[]>([])
const studentList = ref<any[]>([])
const timeline = ref<any[]>([])

// 学生去重（根据 studentId）
const uniqueStudentList = computed(() => {
  const seen = new Set()
  return studentList.value.filter(s => {
    if (seen.has(s.studentId)) return false
    seen.add(s.studentId)
    return true
  })
})

// 获取考试列表（真实接口）
const fetchExams = async () => {
  try {
    const response = await axios.get('/api/exams')
    examList.value = response.data.data.records
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('获取考试列表失败')
  }
}

// 获取学生列表（真实接口）
const fetchStudents = async () => {
  if (!searchForm.examId) return
  try {
    const response = await axios.get(`/api/exams/${searchForm.examId}/students`)
    studentList.value = response.data.data
  } catch (error) {
    console.error('获取学生列表失败:', error)
    ElMessage.error('获取学生列表失败')
  }
}

// 切换考试时，清空学生下拉框
const onExamChange = async () => {
  searchForm.studentId = ''
  await fetchStudents()
}

// 获取回放数据（真实接口）
const fetchReplayData = async () => {
  if (!searchForm.examId || !searchForm.studentId) return
  try {
    const response = await axios.get(`/api/exams/${searchForm.examId}/students/${searchForm.studentId}/replay`)
    timeline.value = response.data.data.map((item: any) => ({
      key: item.key,
      time: item.time,
      type: item.type,
      kind: item.kind,
      eventType: item.eventType,
      desc: item.desc,
      imgUrl: item.imgUrl,
      eventData: item.eventData,
    }))
  } catch (error) {
    console.error('获取回放数据失败:', error)
    ElMessage.error('获取回放数据失败')
  }
}

// 初始化
fetchExams()
</script>

<style scoped>
.exam-replay {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}
.card-header {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
}
.search-form {
  margin-bottom: 20px;
}
.replay-timeline {
  margin-top: 20px;
}
.empty-tip {
  margin-top: 40px;
}

:deep(.el-select),
:deep(.el-form-item__content) {
  min-width: 200px;
}
:deep(.el-select-dropdown) {
  min-width: 220px !important;
}
:deep(.el-select-dropdown__item) {
  white-space: normal;
  word-break: break-all;
  min-width: 200px;
}
</style>
